package com.ruoyi.manage.enterprise.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.celoan.service.ExTradeEffectFinancialproductsDetailService;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.enterprise.domain.PcProductBaseInfo;
import com.ruoyi.manage.enterprise.domain.SysUserExpand;
import com.ruoyi.manage.enterprise.domain.vo.PcProductBaseInfoVo;
import com.ruoyi.manage.enterprise.service.IPcProductBaseInfoService;
import com.ruoyi.manage.enterprise.service.ISysUserExpandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 产品基本信息Controller
 *
 * @author ruoyi
 * @date 2025-08-18
 */
@Api(tags = "产品基本信息控制器")
@RestController
@RequestMapping("/manage/product")
public class PcProductBaseInfoController extends BaseController {
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);
    @Autowired
    private IPcProductBaseInfoService pcProductBaseInfoService;
    @Autowired
    ISysUserExpandService iSysUserExpandService;

    /**
     * 查询产品基本信息列表
     */
    @ApiOperation(value = "查询产品基本信息", notes = "产品基本信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:product:list')" )
    @GetMapping("/list")
    public TableDataInfo list(PcProductBaseInfoVo pcProductBaseInfo, QueryWrapper<PcProductBaseInfo> queryWrapper) {
        setQueryCondition(pcProductBaseInfo, queryWrapper);
        startPage();
        List<PcProductBaseInfo> list = pcProductBaseInfoService.list(queryWrapper);
        return getDataTable(list);
    }


    @ApiOperation(value = "查询产品基本信息", notes = "产品基本信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:product:list')" )
    @GetMapping("/listByOrg")
    public TableDataInfo listByOrg(PcProductBaseInfoVo pcProductBaseInfo, QueryWrapper<PcProductBaseInfo> queryWrapper) {
//        List<SysUserExpand> expandList = iSysUserExpandService.list(new QueryWrapper<SysUserExpand>().eq("user_id", SecurityUtils.getUserId()));
        SysUserExpand userExpand = iSysUserExpandService.lambdaQuery().eq(SysUserExpand::getUserId, SecurityUtils.getUserId()).one();
//        List<String> dataPermissions = expandList.stream().map(m -> m.getDataPermission()).collect(Collectors.toList());
        startPage();
        setQueryCondition(pcProductBaseInfo, queryWrapper);
//        queryWrapper.in("belong_institution",dataPermissions);
        queryWrapper.apply("INSTR(belong_institution,{0})>0", userExpand.getDataPermission());
        List<PcProductBaseInfo> list = pcProductBaseInfoService.list(queryWrapper);
        return getDataTable(list);
    }

    private void setQueryCondition(PcProductBaseInfoVo pcProductBaseInfo, QueryWrapper<PcProductBaseInfo> queryWrapper) {

        if (ObjUtil.isNotNull(pcProductBaseInfo.getApplyTimeRange()) && pcProductBaseInfo.getApplyTimeRange().length > 1) {
            String[] applyTimeRange = pcProductBaseInfo.getApplyTimeRange();
            queryWrapper.between("create_time", applyTimeRange[0], applyTimeRange[1]);
        }
        if (ObjUtil.isNotNull(pcProductBaseInfo.getAuditTimeRange()) && pcProductBaseInfo.getAuditTimeRange().length > 1) {
            String[] auditTimeRange = pcProductBaseInfo.getAuditTimeRange();
            queryWrapper.between("audit_time", auditTimeRange[0], auditTimeRange[1]);
        }

        if (StrUtil.isNotBlank(pcProductBaseInfo.getProductSerialNumber())) {
            queryWrapper.eq(TABLE_PREFIX + "product_serial_number", pcProductBaseInfo.getProductSerialNumber());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getMainGuaranteeWay())) {
            queryWrapper.eq(TABLE_PREFIX + "main_guarantee_way", pcProductBaseInfo.getMainGuaranteeWay());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getAuditStatus())) {
            queryWrapper.eq(TABLE_PREFIX + "audit_status", pcProductBaseInfo.getAuditStatus());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getProductName())) {
            queryWrapper.like(TABLE_PREFIX + "product_name", pcProductBaseInfo.getProductName());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getBelongInstitutionName())) {
            queryWrapper.like(TABLE_PREFIX + "belong_institution_name", pcProductBaseInfo.getBelongInstitutionName());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getProductShortName())) {
            queryWrapper.like(TABLE_PREFIX + "product_short_name", pcProductBaseInfo.getProductShortName());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getProductType())) {
            queryWrapper.eq(TABLE_PREFIX + "product_type", pcProductBaseInfo.getProductType());
        }
        if (StrUtil.isNotBlank(pcProductBaseInfo.getProductLogo())) {
            queryWrapper.eq(TABLE_PREFIX + "product_logo", pcProductBaseInfo.getProductLogo());
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
    }

    /**
     * 导出产品基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:product:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, PcProductBaseInfoVo pcProductBaseInfo, QueryWrapper<PcProductBaseInfo> queryWrapper) {
        if (CollUtil.isEmpty(pcProductBaseInfo.getIds())) {
            setQueryCondition(pcProductBaseInfo, queryWrapper);
        } else {
            queryWrapper.in(TABLE_PREFIX + "id", pcProductBaseInfo.getIds());
        }
        List<PcProductBaseInfo> list = pcProductBaseInfoService.list(queryWrapper);
        ExcelUtil<PcProductBaseInfo> util = new ExcelUtil<PcProductBaseInfo>(PcProductBaseInfo.class);
        util.exportExcel(response, list, "product");
    }

    /**
     * 获取产品基本信息详细信息
     */
    @ApiOperation(value = "获取产品基本信息", notes = "产品基本信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:product:query')" )
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(pcProductBaseInfoService.queryGetById(id));
    }

    @Autowired
    ExTradeEffectFinancialproductsDetailService exTradeEffectFinancialproductsDetailService;

    @PutMapping("/audit")
    public AjaxResult auditContent(@RequestBody PcProductBaseInfo baseInfo) {

        boolean updated = pcProductBaseInfoService.lambdaUpdate().eq(PcProductBaseInfo::getId, baseInfo.getId())
                .set(PcProductBaseInfo::getAuditStatus, baseInfo.getAuditStatus())
                .set(PcProductBaseInfo::getRejectReason, baseInfo.getRejectReason())
                .set(PcProductBaseInfo::getAuditor, SecurityUtils.getLoginUser().getUser().getNickName())
                .set(PcProductBaseInfo::getAuditTime, new Date())
                .update();

//        增加机构上报数据
        if ("1".equals(baseInfo.getAuditStatus())) {
            PcProductBaseInfo productBaseInfo = pcProductBaseInfoService.getById(baseInfo.getId());
            //      增加融资需求上报信息
            ThreadUtil.execAsync(() -> exTradeEffectFinancialproductsDetailService.addFinancialProductsDetail(productBaseInfo));
        }
        return AjaxResult.success(updated);
    }

    /**
     * 新增产品基本信息
     */
    @ApiOperation(value = "新增产品基本信息", notes = "产品基本信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:product:add')" )
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PcProductBaseInfo pcProductBaseInfo) {
        return toAjax(pcProductBaseInfoService.addPcProductBaseInfo(pcProductBaseInfo) ? 1 : 0);
    }

    /**
     * 修改产品基本信息
     */
    @ApiOperation(value = "修改产品基本信息", notes = "产品基本信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:product:edit')" )
    @PutMapping
    public AjaxResult edit(@RequestBody PcProductBaseInfo pcProductBaseInfo) {
        return toAjax(pcProductBaseInfoService.updateById(pcProductBaseInfo) ? 1 : 0);
    }

    /**
     * 修改产品基本信息
     */
    @ApiOperation(value = "修改产品基本信息", notes = "产品基本信息管理")
//    @PreAuthorize("@ss.hasPermi('manage:product:edit')" )
    @PutMapping("/updateBaseInfo")
    public AjaxResult updateBaseInfo(@RequestBody PcProductBaseInfo pcProductBaseInfo) {
        return toAjax(pcProductBaseInfoService.updatePcProductBaseInfo(pcProductBaseInfo) ? 1 : 0);
    }


    /**
     * 修改产品基本信息
     */
    @ApiOperation(value = "修改产品基本信息", notes = "产品基本信息管理")
    @PutMapping("/update")
    public AjaxResult editProduct(@RequestBody PcProductBaseInfo pcProductBaseInfo) {
        return toAjax(pcProductBaseInfoService.updatePcProductBaseInfo(pcProductBaseInfo) ? 1 : 0);
    }

    /**
     * 删除产品基本信息
     */
    @ApiOperation(value = "删除产品基本信息", notes = "产品基本信息管理")
    @PreAuthorize("@ss.hasPermi('manage:product:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(pcProductBaseInfoService.deletePcProductBaseInfoByIds(ids) ? 1 : 0);
    }
}
